package com.csii.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.web.def.NormalExcelConstants;
import com.csii.core.annotation.AutoLog;
import com.csii.core.api.Result;
import com.csii.core.system.base.controller.BaseController;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.util.ConvertUtils;
import com.csii.core.util.oConvertUtils;
import com.csii.user.controller.vo.SysRoleGroupVO;
import com.csii.user.entity.SysRole;
import com.csii.user.entity.SysRoleGroup;
import com.csii.user.entity.SysRoleGroupRelation;
import com.csii.user.model.TreeModel;
import com.csii.user.service.ISysPermissionService;
import com.csii.user.service.ISysRoleGroupService;
import com.csii.user.util.PermissionExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: sys_role_group
 * @Author: power-stdio
 * @Date:   2021-04-27
 * @Version: V1.0
 */
@Api(tags="角色组")
@RestController
@RequestMapping("/sys/roleGroup")
@Slf4j
public class SysRoleGroupController extends BaseController<SysRoleGroup, ISysRoleGroupService> {
	@Autowired
	private ISysRoleGroupService sysRoleGroupService;

	@Autowired
	private ISysPermissionService sysPermissionService;

	/**
	 * 分页列表查询
	 *
	 * @param sysRoleGroupVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="sys_role_group-分页列表查询", notes="sys_role_group-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SysRoleGroupVO sysRoleGroupVO,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		SysRoleGroup sysRoleGroup  = ConvertUtils.convert(SysRoleGroup.class,sysRoleGroupVO);
		QueryWrapper<SysRoleGroup> queryWrapper = QueryGenerator.initQueryWrapper(sysRoleGroup, req.getParameterMap());
		Page<SysRoleGroup> page = new Page<SysRoleGroup>(pageNo, pageSize);
		IPage<SysRoleGroup> pageList = sysRoleGroupService.page(page, queryWrapper);
		IPage<SysRoleGroupVO> pageListVo = ConvertUtils.convertIPage(SysRoleGroupVO.class, pageList);
		return Result.ok(pageListVo);
	}

	/**
	 *   添加
	 *
	 * @param sysRoleGroupVO
	 * @return
	 */
	@AutoLog(value = "sys_role_group-添加")
	@ApiOperation(value="sys_role_group-添加", notes="sys_role_group-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysRoleGroupVO sysRoleGroupVO) {
		SysRoleGroup sysRoleGroup  = ConvertUtils.convert(SysRoleGroup.class,sysRoleGroupVO);
		sysRoleGroupService.save(sysRoleGroup);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param sysRoleGroupVO
	 * @return
	 */
	@AutoLog(value = "sys_role_group-编辑")
	@ApiOperation(value="sys_role_group-编辑", notes="sys_role_group-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SysRoleGroupVO sysRoleGroupVO) {
		SysRoleGroup sysRoleGroup  = ConvertUtils.convert(SysRoleGroup.class,sysRoleGroupVO);
		sysRoleGroupService.updateById(sysRoleGroup);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "sys_role_group-通过id删除")
	@ApiOperation(value="sys_role_group-通过id删除", notes="sys_role_group-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		sysRoleGroupService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "sys_role_group-批量删除")
	@ApiOperation(value="sys_role_group-批量删除", notes="sys_role_group-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.sysRoleGroupService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="sys_role_group-通过id查询", notes="sys_role_group-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SysRoleGroup sysRoleGroup = sysRoleGroupService.getById(id);
		if(sysRoleGroup==null) {
			return Result.error("未找到对应数据");
		}
		SysRoleGroupVO sysRoleGroupVO  = ConvertUtils.convert(SysRoleGroupVO.class,sysRoleGroup);
		return Result.ok(sysRoleGroupVO);
	}

	 @RequestMapping(value = "/queryall", method = RequestMethod.GET)
	 public Result<List<?>> queryall() {
		 Result<List<?>> result = new Result<>();
		 List<?> list = sysRoleGroupService.list();
		 if(list==null||list.size()<=0) {
			 result.error500("未找到角色信息");
		 }else {
			 result.setResult(list);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 /**
	  * 校验角色编码唯一
	  */
	 @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
	 public Result<Boolean> checkCode(String id,String code) {
		 Result<Boolean> result = new Result<>();
		 result.setResult(true);//如果此参数为false则程序发生异常
		 log.info("--验证角色编码是否唯一---id:"+id+"--roleCode:"+code);
		 try {
			 SysRoleGroup role = null;
			 if(oConvertUtils.isNotEmpty(id)) {
				 role = sysRoleGroupService.getById(id);
			 }
			 SysRoleGroup newRole = sysRoleGroupService.getOne(new QueryWrapper<SysRoleGroup>().lambda().eq(SysRoleGroup::getGroupCode, code));
			 if(newRole!=null) {
				 //如果根据传入的roleCode查询到信息了，那么就需要做校验了。
				 if(role==null) {
					 //role为空=>新增模式=>只要roleCode存在则返回false
					 result.setSuccess(false);
					 result.setMessage("角色组编码已存在");
					 return result;
				 }else if(!id.equals(newRole.getId())) {
					 //否则=>编辑模式=>判断两者ID是否一致-
					 result.setSuccess(false);
					 result.setMessage("角色组编码已存在");
					 return result;
				 }
			 }
		 } catch (Exception e) {
			 result.setSuccess(false);
			 result.setResult(false);
			 result.setMessage(e.getMessage());
			 return result;
		 }
		 result.setSuccess(true);
		 return result;
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param sysRoleGroupVO
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysRoleGroupVO sysRoleGroupVO) {
        SysRoleGroup sysRoleGroup  = ConvertUtils.convert(SysRoleGroup.class,sysRoleGroupVO);
        return super.exportXls(request, sysRoleGroup, SysRoleGroup.class, "sys_role_group");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysRoleGroup.class);
    }




	@GetMapping(value = "/exportPermissionXls")
	public ModelAndView exportPermissionXls(String role) {
		LoginUser sysUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String title=sysRoleGroupService.getOne(new LambdaQueryWrapper<>(SysRoleGroup.class).eq(SysRoleGroup::getGroupCode,role)).getGroupName()+"_权限列表";
		ModelAndView mv = new ModelAndView(new PermissionExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		List<TreeModel> treeList = new ArrayList<>();
		sysPermissionService.getTreeModelList(treeList, sysPermissionService.queryByRoleGroup(role), null);
		mv.addObject(NormalExcelConstants.DATA_LIST, treeList);
		return mv;
	}

	@GetMapping(value = "/exportAllPermissionXls")
	public ModelAndView exportPermissionXls() {
		LoginUser sysUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String title="角色组_权限列表";
		ModelAndView mv = new ModelAndView(new PermissionExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		mv.addObject(NormalExcelConstants.DATA_LIST, sysRoleGroupService.list().stream().collect(
				Collectors.toMap(SysRoleGroup::getGroupName,
						a-> { List<TreeModel> treeList = new ArrayList<>();
							sysPermissionService.getTreeModelList(treeList, sysPermissionService.queryByRoleGroup(a.getGroupCode()), null);
							return treeList;})));
		return mv;
	}
}
